/**
 * 
 */
package contegor.scire.structure;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import contegor.scire.core.ReturnPointWaitingObserver;
import contegor.scire.core.StorageResultsReturnPoint;
import contegor.scire.core.TaskId;

class FutureReturnPoint<T> extends StorageResultsReturnPoint<T> implements Future<List<T>> {

  private ReturnPointWaitingObserver wo;
  private boolean done;

  public FutureReturnPoint() {
    this.wo = new ReturnPointWaitingObserver(1);
    this.done = false;
    this.setObserver(wo);
  }

  public void finish(TaskId taskId) {
    this.done = true;
    super.finish(taskId);
  }

  @Override
  public boolean cancel(boolean arg0) {
    throw new UnsupportedOperationException();
  }

  @Override
  public List<T> get() throws InterruptedException, ExecutionException {
    this.wo.await();
    if ((this.exceptions != null) && (this.exceptions.size() > 0))
      throw new ExecutionException(this.exceptions.get(0));
    return this.results;
  }

  @Override
  public List<T> get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
    this.wo.await(timeout, unit);
    if ((this.exceptions != null) && (this.exceptions.size() > 0))
      throw new ExecutionException(this.exceptions.get(0));
    return this.results;
  }

  @Override
  public boolean isCancelled() {
    return false;
  }

  @Override
  public boolean isDone() {
    return this.done;
  }    
}